package org.ai.demo.ocr.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;

@Configuration
@EnableResourceServer
public  class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

	private static final String DEMO_RESOURCE_ID = "api";
	@Autowired 
	private CustomAccessDeniedHandler customAccessDeniedHandler;
	
	@Bean
    public RemoteTokenServices remoteTokenServices() {
		RemoteTokenServices tokenServices = new CustomizedRemoteTokenServices();
//        tokenServices.setClientId("resource_server");
//        tokenServices.setClientSecret("abc123");
        tokenServices.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
//        tokenServices.setCheckTokenEndpointUrl("http://localhost:9030/uaa/oauth/check_token");
        tokenServices.setAccessTokenConverter(new DefaultAccessTokenConverter());
        return tokenServices;
    }
	
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
        resources.authenticationEntryPoint(new AuthExceptionEntryPoint())
        .accessDeniedHandler(customAccessDeniedHandler);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
        .exceptionHandling()
         //定义的不存在access_token时候响应
        .authenticationEntryPoint(new AuthExceptionEntryPoint())
        .and()
        .authorizeRequests().anyRequest().authenticated()
        .and()
        .requestMatchers().antMatchers("/api/**");
    }
}
